package com.shk.service;
import com.alibaba.dubbo.config.annotation.Reference;
import com.shk.pojo.Permission;
import com.shk.pojo.Role;
import com.shk.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/*需要实现 springSecuirity 规定的 UserDetilsService接口来读取数据库中的 用户数据*/

@Component
public class SpringSecurityUserService implements UserDetailsService {
   @Reference
    private UserService userService;
    /*通过用户名来查询用户 并且授予角色 和权限*/
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println(userService);
        System.out.println(username);
        User user = userService.findByUsername(username);
        if(user==null){
            return null;
        }
       List<GrantedAuthority> list = new ArrayList<>();
        /*拿到对应的角色*/
        Set<Role> roles = user.getRoles();
        for(Role role:roles){
            /*获得角色   new SimpleGrantedAuthority() 包装角色和权限数据 */
            list.add(new SimpleGrantedAuthority(role.getKeyword()));
            /*通过角色获取到对应权限*/
            Set<Permission> permissions = role.getPermissions();
            for(Permission permission:permissions){
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        UserDetails userDetails = new org.springframework.security.core.userdetails.User(username,user.getPassword(),list);
        return userDetails;
    }
}
